//
//  MultiSelectView.swift
//  MySwiftTool
//
//  Created by Chris on 2021/4/28.
//

import UIKit



protocol MultiSelectViewDelegate: NSObjectProtocol {
    func selectRangeChanged(_ startIndex: Int, _ endIndex: Int, _ completed: Bool)
}


class MultiSelectView: UIView {

    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.isUserInteractionEnabled = true
        scrollView.backgroundColor = UIColor.white
        return scrollView
    }()

    private lazy var helper: MultiSelectViewHelper = {
        let helper = MultiSelectViewHelper()
        helper.cellHeight = 40
        return helper
    }()

    private var buttons = Array<TouchButton>()
    private var models: Array<Any>?
    weak var delegate: MultiSelectViewDelegate?

    init(_ frame: CGRect, _ models: Array<Any>,_ delegate: MultiSelectViewDelegate) {
        super.init(frame: frame)
        self.models = models
        self.delegate = delegate
        helper.addRangeChangedListner(self, .add, scrollView) { (startIndex, endIndex, completed) in
            self.delegate?.selectRangeChanged(startIndex, endIndex, completed)
        }
        initUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func initUI() {
        addSubview(scrollView)
        scrollView.frame = CGRect.init(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
        initButtons()
        scrollView.contentSize = CGSize.init(width: self.frame.width, height: helper.cellHeight * CGFloat(models!.count))
    }

    func initButtons() {
        let width: CGFloat = self.frame.width
        let height: CGFloat = helper.cellHeight
        for i in 0..<models!.count {
            let button = TouchButton()
            button.setTitle(String(i), for: .normal)
            button.setBackgroundImage(getImageWithColor(color: UIColor.yellow), for: .selected)
            button.setBackgroundImage(getImageWithColor(color: UIColor.yellow), for: .highlighted)
            button.setTitleColor(UIColor.black, for: .normal)
            button.frame = CGRect.init(x: 0.0, y: height * CGFloat(i), width: width, height: height)
            button.tag = i
            button.delegate = helper
            scrollView.addSubview(button)
            buttons.append(button)
        }
        helper.buttons = buttons
    }

    func getImageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}
